//@ts-nocheck
import { name,version } from './../../package.json'

export default function() {
  function checkUpdate() {

    // 模拟请求服务器获取最新版本信息
    uni.request({
      url: `http://47.98.114.76:8001/versions/app/${name}`,
      success: (res) => {
        console.log('checkUpdate', res.data)
        let data = res.data
        if (!data) {
          uni.showToast({ icon: 'error', title: '获取最新版本号失败,网络错误, 请查看网络' })
          console.log('获取最新版本号失败,网络错误, 请查看网络')
          return
        }

        const serverVersionCode = data.version_code
        let result = compareVersions(serverVersionCode, version)
        if (result === 1) {
          showUpdateDialog(data)
        }
      },
    })
  }

  function compareVersions(serverVersionCode, curVersionCode) {
    console.log(`compareVersions: serverVersionCode:${serverVersionCode} curVersionCode:${curVersionCode}`)
    const partsA = serverVersionCode.split('.').map(Number)
    const partsB = curVersionCode.split('.').map(Number)

    const maxLength = Math.max(partsA.length, partsB.length)

    for (let i = 0; i < maxLength; i++) {
      const partA = partsA[i] || 0
      const partB = partsB[i] || 0

      if (partA > partB) return 1
      if (partA < partB) return -1
    }

    return 0
  }

  function showUpdateDialog(updateInfo) {
    console.log('showUpdateDialog')
    uni.showModal({
      title: '发现新版本',
      content: `当前版本: ${version}\n最新版本: ${updateInfo.version_code}\n更新内容:\n${updateInfo.description}`,
      confirmText: '立即更新',
      success: (res) => {
        if (res.confirm) {
          downloadAndInstall(updateInfo.download_url)
        }
      },
    })
  }

  function downloadAndInstall(url) {
    uni.showLoading({ title: '下载中...', mask: true })

    const downloadTask = uni.downloadFile({
      url: url,
      success: (downloadResult) => {
        if (downloadResult.statusCode === 200) {
          plus.runtime.install(downloadResult.tempFilePath, {
            force: true,
          }, () => {
            uni.hideLoading()
            uni.showToast({ title: '安装完成', icon: 'success' })
            plus.runtime.restart()
          }, (error) => {
            uni.hideLoading()
            uni.showToast({ title: `安装失败: ${error}`, icon: 'none', duration: 3000 })
          })
        }
      },
      fail: () => {
        uni.hideLoading()
        uni.showToast({ title: '下载失败', icon: 'none', duration: 3000 })
      },
    })

    // 监听下载进度
    downloadTask.onProgressUpdate((res) => {
      console.log('下载进度：' + res.progress)
    })
  }

  return { checkUpdate }
}